package guoanmaker.operator.business.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.stereotype.Service;

import guoanmaker.operator.business.dao.MonitoringParamsDTO;
import guoanmaker.operator.business.model.OperatorUserDeviceInfo;
import guoanmaker.operator.business.model.ReturnResult;
import guoanmaker.operator.business.repository.OperatorUserDeviceInfoRepository;
import guoanmaker.operator.helper.common.util.HttpGetUtil;
import guoanmaker.operator.helper.common.util.MD5;

/**
 * 
* @ClassName: OperatorToutiaoADDeviceService.java 
* @Description: 评价controller
* @author Cancerl
* @date 2018年5月11日
*  
 */
@Service
public class OperatorToutiaoADDeviceService {
	
	@Autowired
	private OperatorUserDeviceInfoRepository userDeviceInfoRepository;
	
	
	/**
	 * 保存用户的设备信息
	 *
	 * @param monitoringDto 头条下发的监测参数
	 * IOS
	 */
	public void saveCallbackUserDeviceInfoIos(MonitoringParamsDTO monitoringDto) {
//	    //获取监测参数获取用户设备信息
//		OperatorUserDeviceInfo userDeviceInfo = userDeviceInfoRepository.getUserDeviceInfoByParams(monitoringDto);
//	    //不存在用户设备信息，则新建实体
//	    if (ToolsKit.isEmpty(userDeviceInfo)) {
//	        userDeviceInfo = new OperatorUserDeviceInfo();
//	    }
//	    //将头条的下发的检测参数转化为用户设备信息实体
//	    BeanCopier beanCopier = BeanCopier.create(MonitoringParamsDTO.class, OperatorUserDeviceInfo.class, false);
//	    beanCopier.copy(monitoringDto, userDeviceInfo, null);
//	   //此处，您可以再做其他业务逻辑，我在项目重要是累计了用户的点击次数等等 
//	   //保存用户设备信息
//	    userDeviceInfoService.save(userDeviceInfo);
		
		OperatorUserDeviceInfo userDeviceInfo = null;
		//判断设备信息是否存在
		List<OperatorUserDeviceInfo> userDeviceInfos = userDeviceInfoRepository.findByIdfa(monitoringDto.getIdfa());
		if(userDeviceInfos != null && userDeviceInfos.size() > 0){
			//用户存在设备信息
			//点击次数+1
			userDeviceInfo = userDeviceInfos.get(0);
			userDeviceInfo.setCount(userDeviceInfo.getCount() + 1);
		}else{
			userDeviceInfo = new OperatorUserDeviceInfo();
			BeanCopier beanCopier = BeanCopier.create(MonitoringParamsDTO.class, OperatorUserDeviceInfo.class, false);
		    beanCopier.copy(monitoringDto, userDeviceInfo, null);
		    userDeviceInfo.setCount(1);
		    userDeviceInfo.setIscommit(0);
		    userDeviceInfo.setSourcetype(1);
		    userDeviceInfo.setCreatetime(new Date());
		}
		//保存设备信息
		userDeviceInfoRepository.save(userDeviceInfo);
		
	}
	
	/**
	 * 保存用户的设备信息
	 *
	 * @param monitoringDto 头条下发的监测参数
	 * Android
	 */
	public void saveCallbackUserDeviceInfoAndroid(MonitoringParamsDTO monitoringDto) {
		
		OperatorUserDeviceInfo userDeviceInfo = null;
		//判断设备信息是否存在
		//List<OperatorUserDeviceInfo> userDeviceInfos = userDeviceInfoRepository.findByAndroidid(MD5.md5(monitoringDto.getAndroidid()));
		List<OperatorUserDeviceInfo> userDeviceInfos = userDeviceInfoRepository.findByAndroidid(monitoringDto.getAndroidid());
		if(userDeviceInfos != null && userDeviceInfos.size() > 0){
			//用户存在设备信息
			//点击次数+1
			userDeviceInfo = userDeviceInfos.get(0);
			userDeviceInfo.setCount(userDeviceInfo.getCount() + 1);
		}else{
			userDeviceInfo = new OperatorUserDeviceInfo();
			BeanCopier beanCopier = BeanCopier.create(MonitoringParamsDTO.class, OperatorUserDeviceInfo.class, false);
		    beanCopier.copy(monitoringDto, userDeviceInfo, null);
		    userDeviceInfo.setCount(1);
		    userDeviceInfo.setIscommit(0);
		    userDeviceInfo.setSourcetype(1);
		    userDeviceInfo.setCreatetime(new Date());
		}
		//保存设备信息
		userDeviceInfoRepository.save(userDeviceInfo);
	}
	
	/**
	 * 来自自己的设备号保存
	 * 通过激活或注册 保存设备号
	 */
	public ReturnResult saveUserDevice(String deviceid,Integer type,String username,Integer interfaceType){
		ReturnResult result = new ReturnResult();
		if(1==interfaceType){
			result = jihuoService(deviceid, type, username);
		}else if(2==interfaceType){
			result = zhuceService(deviceid, type, username);
		}
		return result;
	}
	
	/**
	 * 激活 
	 */
	public ReturnResult jihuoService(String deviceid,Integer type,String username){
		ReturnResult result = new ReturnResult();
		try{
			//判断设备号是否存在
			List<OperatorUserDeviceInfo> userDeviceInfos = null;
			OperatorUserDeviceInfo userDeviceInfo = null;
			if(0 == type){
				//android
				//userDeviceInfos = userDeviceInfoRepository.findByAndroidid(MD5.md5(deviceid));
				userDeviceInfos = userDeviceInfoRepository.findByAndroidid(deviceid);
			}else if(1 == type){
				//ios
				userDeviceInfos = userDeviceInfoRepository.findByIdfa(deviceid);
			}
			if(userDeviceInfos != null && userDeviceInfos.size() > 0){
				//存在设备号
				//激活时  点击次数+1 
				userDeviceInfo = userDeviceInfos.get(0);
				userDeviceInfo.setCount(userDeviceInfo.getCount() + 1);	//激活  点击次数+1
				
				//存在   设备号   没有进行回调   则进行接口回调
				if(0 == userDeviceInfo.getIscommit() && 1 == userDeviceInfo.getSourcetype()){
					//0 没有上报  进行上报  修改iscommit
					/**
					 * 调用接口2 进行上报  注册设备号
					 */
					callback(userDeviceInfo);
					userDeviceInfo.setIscommit(1);
					userDeviceInfo.setValidatetime(new Date());
				}
			}else{
				//不存在设备号
				//添加新的设备号记录
				userDeviceInfo = new OperatorUserDeviceInfo();
				if(0 == type){
					userDeviceInfo.setAndroidid(deviceid);
				}else if(1==type){
					userDeviceInfo.setIdfa(deviceid);
				}
				userDeviceInfo.setIscommit(1);
				userDeviceInfo.setCount(1);
				userDeviceInfo.setOs(type+"");
				userDeviceInfo.setSourcetype(0);
				userDeviceInfo.setCreatetime(new Date());
			}
			if(userDeviceInfo != null){
				userDeviceInfoRepository.save(userDeviceInfo);
			}
			result.setKey("success");
			result.setValue("激活  设备号保存成功");
		}catch (Exception e) {
			e.printStackTrace();
			result.setKey("error");
			result.setValue("激活  设备号保存失败");
		}
		return result;
	}
	
	/**
	 * 注册 
	 */
	public ReturnResult zhuceService(String deviceid,Integer type,String username){
		ReturnResult result = new ReturnResult();
		try{
			//判断设备号是否存在
			List<OperatorUserDeviceInfo> userDeviceInfos = null;
			OperatorUserDeviceInfo userDeviceInfo = null;
			if(0 == type){
				//android
				//userDeviceInfos = userDeviceInfoRepository.findByAndroidid(MD5.md5(deviceid));
				userDeviceInfos = userDeviceInfoRepository.findByAndroidid(deviceid);
			}else if(1 == type){
				//ios
				userDeviceInfos = userDeviceInfoRepository.findByIdfa(deviceid);
			}
			if(userDeviceInfos != null && userDeviceInfos.size() > 0){
				//存在设备号
				//注册  拼接注册手机号
				userDeviceInfo = userDeviceInfos.get(0);
				String userPhone = (userDeviceInfo.getPhone() == null || "".equals(userDeviceInfo.getPhone())) ? username :  userDeviceInfo.getPhone() + ";" + username;
				userDeviceInfo.setPhone(userPhone);	//拼接注册的手机号
				/*if(0 == userDeviceInfo.getIscommit()){
					//0 没有上报  进行上报  修改iscommit
					*//**
					 * 调用接口2 进行上报  注册设备号
					 *//*
					userDeviceInfo.setIscommit(1);
				}*/
			}else{
				//不存在设备号
				//添加新的设备号记录
				userDeviceInfo = new OperatorUserDeviceInfo();
				if(0 == type){
					userDeviceInfo.setAndroidid(deviceid);
				}else if(1==type){
					userDeviceInfo.setIdfa(deviceid);
				}
				userDeviceInfo.setIscommit(1);
				userDeviceInfo.setCount(1);
				userDeviceInfo.setOs(type+"");
				userDeviceInfo.setSourcetype(0);
				userDeviceInfo.setCreatetime(new Date());
			}
			if(userDeviceInfo != null){
				userDeviceInfoRepository.save(userDeviceInfo);
			}
			result.setKey("success");
			result.setValue("注册  设备号保存成功");
		}catch (Exception e) {
			e.printStackTrace();
			result.setKey("error");
			result.setValue("注册  设备号保存失败");
		}
		return result;
	}
	
	/**
     * 激活回调
     *
     * @param userDeviceInfo 用户设备信息
     */
	public void callback(OperatorUserDeviceInfo userDeviceInfo){
		String os = userDeviceInfo.getOs();
		String muid = null; //安卓取imei进行MD5加密，ios取idfa
		if ("0".equals(os)) {
            //muid赋值
            String imei = userDeviceInfo.getImei();
            muid = MD5.md5(imei);
        } else if ("1".equals(os)) {
            muid = userDeviceInfo.getIdfa();
        }
		//String TOU_TIAO_ACTIVATE_URL="http://ad.toutiao.com/track/activate/?";
		String TOU_TIAO_ACTIVATE_URL="http://ad.toutiao.com/track/activate/?"
		+"callback=%s&muid=%s&os=%s&conv_time=%s&event_type=%d";
        //回调url设置，回调参数
        String url = String.format(TOU_TIAO_ACTIVATE_URL, userDeviceInfo.getCallback(), muid, os, userDeviceInfo.getTimestamp(),0);
        //对url进行签名
        //url = getSignatureUrl(url, os);
//        call2TouTiao(url, userDeviceInfo);
//        System.out.println(url);
        HttpGetUtil.httpBigGet(url);
	}
	
}
